package seller

import (
	"dhfshop/models"
	"dhfshop/models/consts"
	"errors"
	"strings"
	"time"
	"github.com/astaxie/beego/orm"
)

//公共打印模板管理
type PrintPub struct {
	PrintPubId      int64     `orm:"column(print_pub_id);pk;auto" json:"print_pub_id" form:"print_pub_id"`  //自增主键
	Name            string    `orm:"column(name)" json:"name" form:"name"`                           //模板名称
    ShippingCorp    string    `orm:"column(shipping_corp);null" json:"shipping_corp" form:"shipping_corp"`   /*物流公司  */
	TypeId          int       `orm:"column(type_id);default(1);index" json:"type_id" form:"type_id"`  //类型
	StatusId        int       `orm:"column(status_id);default(0)" json:"status_id" form:"status_id"`  //默认0=草稿，1=发布（商家可见）
    TepType         int       `orm:"column(tep_type);default(0)" json:"tep_type" form:"tep_type"`     //默认0,模板类型
	Content         string    `orm:"column(content);type(text);null" json:"content" form:"content"`  //模板内容
	Size            string    `orm:"column(size);null" json:"size" form:"size"`                      //尺寸
	Image           string    `orm:"column(image);null" json:"image" form:"image"`                   //图片链接
	DefaultPrinter  string    `orm:"column(default_printer);null" json:"default_printer" form:"default_printer"` //默认打印机
	DefaultTemplate bool      `orm:"column(default_template)" json:"default_template" form:"default_template"`   //默认模板
	DefaultExpress  bool      `orm:"column(default_express)" json:"default_express" form:"default_express"`      //默认快递公司
	CreatedAt       time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`     //创建时间
	CreatedAtStr    string    `orm:"-" json:"created_at,omitempty" form:"-"`
	XiaoPiaoType    string    `orm:"column(xiaopiao_type);size(10);null" json:"xiaopiao_type" form:"xiaopiao_type"`
}

func init() {
	orm.RegisterModel(new(PrintPub))
}

// 查询
func GetPrintPub(id int64) (v *PrintPub, err error) {
	o := models.GetDefaultDB()
	v = &PrintPub{PrintPubId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// 添加
func AddPrintPub(v *PrintPub) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

// 更新
func UpdatePrintPub(m *PrintPub, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := PrintPub{PrintPubId: m.PrintPubId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, k...)
		return
	}
	return
}

// 删除
func DeletePrintPub(id int64) (err error) {
	o := models.GetDefaultDB()
	v := PrintPub{PrintPubId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

// 批量查询
func GetAllPrintPubs(query map[string]string, fields []string, order_by map[string]string, offset, limit int) ([]*PrintPub, int64, error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PrintPub))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, ","); ok {
			valueArr := strings.Split(v, ",")
			qs = qs.Filter(k, valueArr)
		} else {
			qs = qs.Filter(k, v)
		}
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*PrintPub
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, temp := range lists {
			temp.CreatedAtStr = temp.CreatedAt.Format(consts.DATETIME_FORMAT)
		}
		return lists, cnt, nil
	}
	return nil, 0, err
}
